package cn.cjj.gulimall.search.service.impl;

import cn.cjj.common.to.es.SkuEsModel;
import cn.cjj.gulimall.search.config.GulimallElasticSearchConfig;
import cn.cjj.gulimall.search.constant.EsConstant;
import cn.cjj.gulimall.search.service.ElasticSaveService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author CuiJunJie
 * @create 2021/6/21-15:42
 */
@Slf4j
@Service
public class ElasticSaveServiceImpl implements ElasticSaveService {

    @Autowired
    RestHighLevelClient client;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws Exception{
        BulkRequest bulkRequest = new BulkRequest();

        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        System.out.println(client.toString());

        BulkResponse bulk = client.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        boolean b = bulk.hasFailures();
        if (b) {
            log.error("ElasticSearch 出错了");
            for (BulkItemResponse respons : bulk) {
                if (respons.isFailed()) {
                    log.error(respons.getFailureMessage());
                }
            }
        } else {
            for (BulkItemResponse response : bulk) {
                DocWriteResponse itemResponse = response.getResponse();
                    IndexResponse indexResponse = (IndexResponse) itemResponse;
                    System.out.println(indexResponse.toString());
            }
        }

        return !b;
    }
}
